"""Intel CPU 功耗采样后端（通过 RAPL）"""

from __future__ import annotations
from typing import Optional
import os
import time

from .base import PowerBackend


class RAPLBackend(PowerBackend):
    """Intel CPU 功耗采样（通过 RAPL - Running Average Power Limit）"""
    
    def __init__(self):
        self._rapl_path = "/sys/class/powercap/intel-rapl"
        self._last_energy = None
        self._last_timestamp = None
        self._device_id = 0
    
    @staticmethod
    def is_available() -> bool:
        return os.path.exists("/sys/class/powercap/intel-rapl/intel-rapl:0/energy_uj")
    
    def init(self, device_id: int = 0) -> bool:
        self._device_id = device_id
        try:
            # 读取初始能耗值
            with open(f"{self._rapl_path}/intel-rapl:{device_id}/energy_uj", "r") as f:
                self._last_energy = int(f.read().strip())
            self._last_timestamp = time.perf_counter()
            return True
        except:
            return False
    
    def sample(self) -> Optional[float]:
        try:
            # 读取当前能耗值（微焦耳）
            with open(f"{self._rapl_path}/intel-rapl:{self._device_id}/energy_uj", "r") as f:
                current_energy = int(f.read().strip())
            current_time = time.perf_counter()
            
            # 计算功率（能耗差 / 时间差）
            if self._last_energy is not None:
                delta_energy_uJ = current_energy - self._last_energy
                delta_time_s = current_time - self._last_timestamp
                
                if delta_time_s > 0:
                    power_W = (delta_energy_uJ / 1e6) / delta_time_s
                    power_mW = power_W * 1000.0
                    
                    # 更新状态
                    self._last_energy = current_energy
                    self._last_timestamp = current_time
                    return power_mW
            
            return None
        except:
            return None
    
    def cleanup(self):
        pass
    
    def get_name(self) -> str:
        return "rapl"

